//
//  ContactTableViewController.m
//  AddressBook
//
//  Created by 解晓东 on 15/11/7.
//  Copyright (c) 2015年 sasa. All rights reserved.
//

#import "ContactTableViewController.h"
#import "SAContactModel.h"
#import "AddViewController.h"
#import "EditViewController.h"

#define CONTACTFILEPATH [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"contacts.data"]

@interface ContactTableViewController () <AddViewControllerDelegate, EditViewControllerDelegate>

@property (nonatomic, strong) NSMutableArray *contactArr;

- (IBAction)backAction:(id)sender;

@end

@implementation ContactTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self clearExtraLine:self.tableView];
}

#pragma mark - 联系人数组懒加载
- (NSMutableArray *)contactArr {
    if (!_contactArr) {
        // 如果没有数组就创建
        _contactArr = [NSKeyedUnarchiver unarchiveObjectWithFile:CONTACTFILEPATH];
        if (_contactArr == nil) {
            _contactArr = [NSMutableArray array];
        }
    }
    
    return _contactArr;
}

- (IBAction)backAction:(id)sender {
    // 初始化
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"是否注销？" message:@"真的要注销吗" preferredStyle:UIAlertControllerStyleActionSheet];
    // 添加取消按钮
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    // 添加确定按钮
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
        [self.navigationController popViewControllerAnimated:NO];
    }]];
    // 弹出
    [self presentViewController:alert animated:YES completion:NULL];
}

#pragma mark - 列表操作
// 分组为1
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

// 返回数组的个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.contactArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"mycell"];
    
    SAContactModel *contactModel = self.contactArr[indexPath.row];
    cell.textLabel.text = contactModel.name;
    cell.detailTextLabel.text = contactModel.phone;
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
    return cell;
}

#pragma mark - AddViewController delegate
- (void)addContact:(AddViewController *)addVc didAddContact:(SAContactModel *)contact {
    // 1. 添加数据模型
    [self.contactArr addObject:contact];
    // 2. 刷新表视图
    [self.tableView reloadData];
    // 3.归档
    [NSKeyedArchiver archiveRootObject:self.contactArr toFile:CONTACTFILEPATH];
}

#pragma mark - UITableView delegate
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    // 删除功能
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // 1.删除数据模型
        [self.contactArr removeObjectAtIndex:indexPath.row];
        // 2.刷新表视图
        [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationTop];
        // 3.归档
        [NSKeyedArchiver archiveRootObject:self.contactArr toFile:CONTACTFILEPATH];
    }
}

#pragma mark - Navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // 设置代理对象
    // AddViewController *addVc = segue.destinationViewController;
    // addVc.delegate = self;
    id vc = segue.destinationViewController;// 拿到目的控制器
    if ([vc isKindOfClass:[AddViewController class]]) {
        // 如果是跳转到添加联系人控制器
        AddViewController *addVc = vc;
        addVc.delegate = self;
    } else if ([vc isKindOfClass:[EditViewController class]]) {
        EditViewController *editVc = vc;
        // 取得选中的那一行
        NSIndexPath *path = [self.tableView indexPathForSelectedRow];
        editVc.contactModel = self.contactArr[path.row];
        editVc.delegate = self; // 设置代理对象
    }
}

#pragma mark - EditVc delegate
- (void)editViewController:(EditViewController *)deitVc didSaveContact:(SAContactModel *)model {
    [self.tableView reloadData];
    // 归档
    [NSKeyedArchiver archiveRootObject:self.contactArr toFile:CONTACTFILEPATH];
}

#pragma mark - 去掉多余的线
- (void)clearExtraLine:(UITableView *)tableView {
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = [UIColor clearColor];
    [self.tableView setTableFooterView:view];
}

@end
